package com.truongnha.clienttn.data.sao;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import com.truongnha.clienttn.business.model.TeacherAttendModel;
import com.truongnha.clienttn.data.dao.AccountDAO;
import com.truongnha.clienttn.data.dao.CreateDatabase;
import com.truongnha.clienttn.data.dao.TeacherAttendDAO;
import com.truongnha.clienttn.data.entity.AccountEntity;
import com.truongnha.clienttn.data.servicehelper.utils;
import com.truongnha.clienttn.presentation.temp.JSONParser;

import config.Url;

import android.content.Context;
import android.util.Log;

public class TeacherAttendSAO {
	private Context context;
	private String url;
	private int classId;
	private int day;
	private int month;
	private int year;

	public TeacherAttendSAO(Context context) {
		super();
		this.context = context;
	}

	public TeacherAttendSAO(Context context, int classId, int day, int month,
			int year) {
		this.context = context;
		this.classId = classId;
		this.day = day;
		this.month = month;
		this.year = year;
		this.url = Url.getURLGetAttendanceTeacher() + classId + "/" + day + "/"
				+ month + "/" + year + "/";
	}

	public void getDataFromServer() {
		String data = utils.getStringJSON(url);
		saveToDatabase(data);

	}

	private void saveToDatabase(String data) {
		Log.d("LOG", "Teacher attend SAO 2.1");
		try {
			CreateDatabase db = new CreateDatabase(context);
			TeacherAttendDAO teacherAttendDAO = new TeacherAttendDAO(db.open());
			teacherAttendDAO.delete();
			teacherAttendDAO.insert(data, classId, day, month, year);
			db.close();
		} catch (Exception e) {
			Log.d("LOG", "Teacher attend SAO 2.5" + e.toString());
		}
	}

	public void submitAttendance(TeacherAttendModel teacherAttendModel,
			String date) {

		CreateDatabase db = new CreateDatabase(context);
		AccountDAO accountDAO = new AccountDAO(db.open());
		AccountEntity accountEntity = accountDAO.getCurrentAccount();
		db.close();

		String csrfmiddlewaretoken = accountEntity.getCsrftoken();
		String data = teacherAttendModel.getId() + "-"
				+ teacherAttendModel.getStatusString() + "-" + date;
		String url = Url.getURLPostAttendanceTeacher();

		Log.d("log", data + " dfdsf  " + date);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("date", date));
		// To do
		params.add(new BasicNameValuePair("list", data));
		params.add(new BasicNameValuePair("csrfmiddlewaretoken",
				csrfmiddlewaretoken));
		JSONParser jsonParser = new JSONParser();
		int statusCode = jsonParser.postSubmit(url, params);

	}
}
